<template>
  <div class="manager_user">
    <section class="manager_user_header">
      <a-card>
        <a-form name="advanced_search" autocomplete="off" ref="searchFormRef" class="ant-advanced-search-form"
          :model="searchFormState">
          <a-row :gutter="24">
            <a-col :span="8">
              <a-form-item name="username" label="用户名">
                <a-input v-model:value="searchFormState.username" placeholder="请输入用户名" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="realName" label="真实姓名">
                <a-input v-model:value="searchFormState.realName" placeholder="请输入真实姓名" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="nickname" label="昵称">
                <a-input v-model:value="searchFormState.nickname" placeholder="请输入昵称" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="8">
              <a-form-item name="telephone" label="手机号">
                <a-input v-model:value="searchFormState.telephone" placeholder="请输入手机号" allowClear />
              </a-form-item>
            </a-col>
            <a-col :span="16">
              <a-form-item name="status" label="状态">
                <a-radio-group v-model:value="searchFormState.status" name="status">
                  <a-radio :value="1">正常</a-radio>
                  <a-radio :value="2">冻结</a-radio>
                </a-radio-group>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-button type="primary" @click="handleSearch">查询</a-button>
              <a-button style="margin: 0 8px" @click="handleReset">重置</a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </section>
    <section class="manager_user_content">
      <a-card style="height: 100%">
        <a-row style="margin-top: 8px;">
          <a-col :span="24">
            <a-table :dataSource="dataSource" :columns="columns" size="small" :pagination="false" :scroll="{ x: 1000 }">

              <template #bodyCell="{ column, record }">
                <template v-if="column.dataIndex === 'avatar'">
                  <a-image :src="record?.avatar" :width="100" :height="60" v-if="record?.avatar" />
                </template>
                <template v-if="column.dataIndex === 'status'">
                  <a-badge status="success" v-if="record.status === 1" text="正常" />
                  <a-badge status="error" v-if="record.status === 2" text="冻结" />
                </template>
                <a-space v-if="column.dataIndex === 'operation'">
                  <a-button type="link" @click="handleEdit(record)">编辑</a-button>
                  <a-popconfirm title="确定要删除这条数据吗？" ok-text="确定" cancel-text="取消" @confirm="handleDelete(record.id)">
                    <a-button type="link" danger>删除</a-button>
                  </a-popconfirm>

                </a-space>
              </template>
            </a-table>
          </a-col>
        </a-row>
      </a-card>
    </section>
    <footer class="manager_user_footer">
      <a-card style="height: 100%;">
        <a-row align="middle">
          <a-col :span="24">
            <a-pagination :total="total" v-model:current="current" v-model:pageSize="pageSize" :showSizeChanger="true"
              showQuickJumper :show-total="total => `共 ${total} 条数据`" @change="onPageChange" />
          </a-col>
        </a-row>
      </a-card>
    </footer>
    <a-modal v-model:open="open" :title="title" @ok="handleOk" :confirm-loading="confirmLoading" :destroyOnClose="true"
      centered :maskClosable="false">

      <a-form :ref="formRef" :model="formState" autocomplete="off" v-bind="layout">
        <a-form-item label="头像" name="avatar">
          <SingleImageUploader name="avatar" :defaultUrl="formState.avatar ? `/api${formState.avatar}` : null"
            @upload-success="(filePath) => {
              formState.avatar = `${filePath}`;
            }" />
        </a-form-item>
        <a-form-item label="真实姓名" name="realName">
          <a-input v-model:value="formState.realName" allowClear placeholder="请输入真实姓名" />
        </a-form-item>
        <a-form-item label="昵称" name="nickname">
          <a-input v-model:value="formState.nickname" allowClear placeholder="请输入昵称" />
        </a-form-item>
        <a-form-item label="电话" name="telephone">
          <a-input v-model:value="formState.telephone" allowClear placeholder="请输入电话" />
        </a-form-item>
        <a-form-item label="邮箱" name="email">
          <a-input v-model:value="formState.email" allowClear placeholder="请输入邮箱" />
        </a-form-item>
        <a-form-item label="邮箱" name="birthday">
          <a-date-picker v-model:value="formState.birthday" style="width: 100%;" allowClear placeholder="请选择出生日期" />
        </a-form-item>
        <a-form-item name="sex" label="性别">
          <a-radio-group v-model:value="formState.sex" name="sex">
            <a-radio :value="1">男</a-radio>
            <a-radio :value="2">女</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </a-modal>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { message } from 'ant-design-vue';
import SingleImageUploader from '@/components/common/SingleImageUploader/index.vue';
import { getUserList, addUser, editUser, deleteUser } from '@/apis/user';
import dayjs from 'dayjs';

const layout = {
  labelCol: {
    span: 4,
  },
  wrapperCol: {
    span: 20,
  },
};
const searchFormRef = ref();
const formRef = ref();
const dataSource = ref([]);
const searchFormState = ref({
  username: "",
  realName: "",
  nickname: "",
  telephone: "",
  status: null
});
const formState = ref({
  id: "",
  realName: "",
  nickname: "",
  telephone: "",
  email: "",
  sex: null,
  birthday: "",
});

const current = ref(1);
const total = ref(0);
const pageSize = ref(10);
const handleSearch = async () => {
  try {
    const { data = {} } = await getUserList({
      pageNum: current.value,
      pageSize: pageSize.value,
      ...searchFormState.value
    });
    dataSource.value = data?.list;
    total.value = data?.total;
  } catch (error) {
    console.log(error, 'get-user-list-error');
  }

};
const open = ref(false);
const title = ref('');
const confirmLoading = ref(false);
let handleType = '';

const handleEdit = (record) => {

  formState.value = {
    ...record,
    birthday: dayjs(record.birthday),
  };
  open.value = true;
  title.value = '编辑用户';
  handleType = 'edit';
};

const handleDelete = async (id) => {
  await deleteUser(id);
  init();
  message.success('操作成功');
};
const handleOk = async () => {
  confirmLoading.value = true;
  if (handleType === 'add') {
    await addUser({
      ...formState.value,
    });
  } else {
    await editUser({
      ...formState.value,
      birthday: formState.value.birthday.format('YYYY-MM-DD'),
    });
  }
  init();
  message.success('操作成功');
  open.value = false;
  confirmLoading.value = false;
  title.value = '';
};
const onPageChange = (page, Size) => {
  current.value = page;
  pageSize.value = Size;
  init();
};

const handleReset = () => {
  searchFormRef.value?.resetFields();
  init();
};
const init = async () => {
  try {
    const { data = {} } = await getUserList({
      pageNum: current.value,
      pageSize: pageSize.value,
    });
    dataSource.value = data?.list;
    total.value = data?.total;
  } catch (error) {
    console.log(error, 'get-user-list-error');
  }
};

onMounted(() => {
  init();
});


const columns = [
  {
    title: '头像',
    dataIndex: 'avatar',
    width: 160,
    align: 'center',
  },
  {
    title: '用户名',
    dataIndex: 'username',
    width: 160,
    align: 'center',
  },
  {
    title: '昵称',
    dataIndex: 'nickname',
    width: 160,
    align: 'center',
  },
  {
    title: '真实姓名',
    dataIndex: 'realName',
    width: 140,
    align: 'center'
  },
  {
    title: '手机号',
    dataIndex: 'telephone',
    width: 160,
    align: 'center'
  },
  {
    title: '邮箱',
    dataIndex: 'email',
    width: 160,
    align: 'center'
  },
  {
    title: '性别',
    dataIndex: 'gender',
    width: 140,
    align: 'center'
  },
  {
    title: '生日',
    dataIndex: 'birthday',
    width: 140,
    align: 'center'
  },
  {
    title: '余额',
    dataIndex: 'amount',
    width: 120,
    align: 'center'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    align: 'center',
  },
  {
    title: '操作',
    dataIndex: 'operation',
    fixed: 'right',
    width: 130,
    align: 'center'
  },
]
</script>

<style lang="less" scoped>
.manager_user {
  box-sizing: border-box;
  padding: 8px;
  display: flex;
  flex-direction: column;
  height: 100%;

  &_header {
    width: 100%;
    max-height: 200px;
  }

  &_content {
    margin-top: 8px;
    flex: 1;
    overflow: auto;
  }

  &_footer {
    margin-top: 8px;
    height: 80px;
  }
}
</style>
